package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"manuscript-service/model/mysql"

	"manuscript-service/servicerpc/internal/svc"
	"manuscript-service/servicerpc/servicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ServiceAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewServiceAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServiceAddLogic {
	return &ServiceAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *ServiceAddLogic) ServiceAdd(in *servicerpc.ServiceAddRequest) (*servicerpc.ServiceAddResponse, error) {
	// todo: add your logic here and delete this line
	var FindService mysql.Service
	begin := mysql.DB.Begin()
	if err := FindService.FindServiceByTitle(mysql.DB, in.Title); err == nil {
		begin.Rollback()
		return nil, errors.New("商品已存在")
	}

	class := mysql.Class{
		Model:     gorm.Model{},
		ClassName: in.ClassName,
	}
	if err := class.FindClassByName(mysql.DB, class.ClassName); err != nil {
		begin.Rollback()
		return nil, err
	}

	service := mysql.Service{
		Model:   gorm.Model{},
		Title:   in.Title,
		Like:    int(in.Like),
		Commit:  int(in.Commit),
		ClassId: int(class.ID),
	}
	if err := service.ServiceAdd(mysql.DB); err != nil {
		begin.Rollback()
		return nil, err
	}
	begin.Commit()
	return &servicerpc.ServiceAddResponse{
		ServiceId: int64(service.ID),
	}, nil
}
